<template>
  <div class="app-container">
    <el-row>
      <el-form ref="form" :model="queryParams" label-width="80px">
        <el-col :span="6">
          <el-form-item label="主体名称">
            <el-input v-model="queryParams.companyName" size="small"
                      placeholder="请输入主体名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="注册手机号">
            <el-input v-model="queryParams.mobilePhone" size="small"
                      placeholder="请输入注册手机号码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否会员">
            <el-select v-model="queryParams.memberFlag" size="small"
                       placeholder="请选择是否会员" style="width: 240px">
              <!--在value属性前添加冒号（:）， 用于解决值类型不匹配问题-->
<!--              <el-option label="非会员" :value="0"></el-option>-->
<!--              <el-option label="会员" :value="1"></el-option>-->
<!--             使用字典方式 -->
              <el-option
                v-for="dict in dict.type.njt_member_flag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>


        </el-col>
        <template v-if="toggleContent">
          <el-col :span="6">
            <el-form-item label="用户状态">
              <el-select v-model="queryParams.userStatus" size="small" placeholder="请选择用
户状态" style="width: 240px">
                <el-option label="正常" :value="0"></el-option>
                <el-option label="冻结" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="6">
          <el-form-item label-width="0" style="margin-left: 20px">
            <el-button type="primary" icon="el-icon-search" size="small"
                       style="margin-right: 10px" @click="getPage">搜索</el-button>
            <el-button type="primary" icon="el-icon-refresh" size="small" @click="resetQuery">重
              置</el-button>
            <a style="margin-left: 10px;color: #3a8ee6"
               @click="toggleContentHandle">
              {{toggleContent ? '收起' : '展开'}}
              <i v-if="toggleContent" class="el-icon-arrow-up"></i>
              <i v-else class="el-icon-arrow-down"></i>
            </a>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-button type="primary" icon="el-icon-download" size="medium"
                   style="margin-right: 10px" @click="handleExport">导出</el-button>
        <el-button type="danger" icon="el-icon-delete" size="medium"  @click="handleBatchDelete">批量删除</el-button>
      </el-col>
    </el-row>
    <!-- 表格区域-->
    <el-row style="margin-top: 20px">
      <el-col :span="24">
        <!--border:当布尔属性默认值为false时，显式的使用该属性，就表示设置该属性为true-->
        <el-table :data="tableData" style="width: 100%" border ref="table">

        <el-table-column type="selection" width="55" align="center"></el-table-column>
          <el-table-column prop="companyName" label="主体名称" width="280"
                           align="center"></el-table-column>
          <el-table-column prop="mobilePhone" label="注册手机号" width="180"
                           align="center"></el-table-column>
          <el-table-column prop="registerTime" label="注册时间" align="center" width="180">
          </el-table-column>

          <el-table-column label="是否会员" align="center">
            <!--自定义列渲染，固定模版，借助关键字scope，可以获取当前表格行数据，用法：
            scope.row.对象属性名-->
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.memberFlag == 0">非会员</el-tag>
              <el-tag type="success" v-else-if="scope.row.memberFlag == 1">会员</el-tag>
              <el-tag type="info" v-else>错误</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="信息是否完善" align="center">
            <!--自定义列渲染，固定模版，借助关键字scope，可以获取当前表格行数据，用法：
            scope.row.对象属性名-->
            <template slot-scope="scope">
              <dict-tag :options="dict.type.njt_perfect_flag" :value="scope.row.perfectFlag"/>
            </template>
          </el-table-column>
          <el-table-column label="用户状态" align="center">
            <template slot-scope="scope">
              <el-tag type="danger" v-if="scope.row.userStatus == 0">正常</el-tag>
              <el-tag type="success" v-else-if="scope.row.userStatus == 1">冻结</el-tag>
              <el-tag type="info" v-else>错误</el-tag>
            </template>

          </el-table-column>
          <el-table-column prop="completionTime" label="信息完善时间" align="center"  width="180">
          </el-table-column>
          <el-table-column prop="trialTime" label="试用到期时间" align="center"  width="180">
          </el-table-column>
          <el-table-column prop="purchaseTime" label="购买会员时间" align="center"  width="180">
          </el-table-column>
          <el-table-column prop="expirationDate" label="会员过期时间" align="center"  width="180">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="100" align="center" >
            <template slot-scope="scope">
              <el-button type="text" size="small"
                         @click="openDialog(scope.row)">编辑</el-button>
              <el-button type="text" size="small" style="color:red" @click="deleteByUserId(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <el-dialog title="编辑" :visible.sync="dialogVisible" width="30%">
      <!--添加表单组件-->
      <el-form ref="updateForm" :model="editObjects" label-width="100px">
        <el-form-item label="主体名称">
          <el-input v-model="editObjects.companyName" placeholder="请输入主体名
称"></el-input>
        </el-form-item>
        <el-form-item label="注册手机号">
          <el-input v-model="editObjects.mobilePhone" placeholder="请输入注册手机号">
          </el-input>
        </el-form-item>
        <el-form-item label="注册时间">
          <el-date-picker
            v-model="editObjects.registerTime"
            type="datetime"
            placeholder="请选择注册时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"    style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="是否会员">
          <el-select v-model="editObjects.memberFlag" placeholder="请选择活动区
域">
<!--            <el-option label="非会员" :value="0"></el-option>-->
<!--            <el-option label="会员" :value="1"></el-option>-->
            <el-option
              v-for="dict in dict.type.njt_member_flag"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />

          </el-select>
        </el-form-item>

        <el-form-item label="信息完善时间">
          <el-date-picker
            v-model="editObjects.completionTime"
            type="datetime"
            placeholder="请选择信息完善时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"    style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试用到期时间">
          <el-date-picker
            v-model="editObjects.trialTime"
            type="datetime"
            placeholder="请选择试用到期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"    style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="购买会员时间">
          <el-date-picker
            v-model="editObjects.purchaseTime"
            type="datetime"
            placeholder="请选择购买会员时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"    style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="会员过期时间">
          <el-date-picker
            v-model="editObjects.expirationDate"
            type="datetime"
            placeholder="请选择会员过期时间"
            format="yyyy-MM-dd HH:mm:ss"
            value-format="yyyy-MM-dd HH:mm:ss"    style="width: 100%">
          </el-date-picker>
        </el-form-item>

        <el-form-item label="用户状态">
          <el-select v-model="editObjects.userStatus" placeholder="请选择活动区域">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="冻结" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!--对话框底部按钮组，固定代码结构-->
      <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitData">确 定</el-button>
      </span>
    </el-dialog>

    <el-row>
      <el-col :span="24" style="margin-top: 20px" align="center">
        <el-pagination layout="prev, pager, next"
                       @current-change="getPageByPageNum"
                       :page-size="queryParams.pageSize"
                       :total="total"
                       :current-page="queryParams.pageNum"></el-pagination>
      </el-col>
    </el-row>

    <!-- 弹窗区域：一般用于新增或编辑弹窗-->

  </div>
</template>
<script>
import {listNjtUserRegister, updateNjtUserRegister, deleteNjtUserRegister,batchDeleteNjtUserRegister} from "@/api/njt/user/register";

export default {
  name: "XXX",
  dicts:['njt_member_flag','njt_perfect_flag','njt_user_status'],
  data() {
    return {
      /** 查询条件 */
      queryParams: {
        pageNum:1,
        pageSize:5,
        companyName: "",// 主体名称
        mobilePhone: "",// 注册手机号码
        memberFlag: undefined, // 是否会员，0表示非会员，1表示会员
        userStatus: undefined, // 用户状态，0表示正常，1表示冻结
        completionTime:"",
        trialTime:"",
        purchaseTime:"",
        expirationDate:"",
      },
      /** 切换搜索区域内容 */
      toggleContent: false, // 默认隐藏，值为true时显示
      /** 数据总条数 */
      total:56,
      tableData: [],
      /** 编辑对话框控制 */
      dialogVisible: false,// 默认不显示对话框
      /** 编辑对话框绑定对象 */
      editObjects:{
        companyName: "",// 主体名称
        mobilePhone: "",// 注册手机号码
        registerTime: "",// 注册时间
        memberFlag: undefined, // 是否会员，0表示非会员，1表示会员
        userStatus: undefined, // 用户状态，0表示正常，1表示冻结
        completionTime:"",
        trialTime:"",
        purchaseTime:"",
        expirationDate:"",
      }
    }

  },
  created() {
    this.getPage()
  },
  methods: {
    //删除按钮操作
    deleteByUserId(userId) {
      this.$modal.confirm('是否确认删除用户编号为"' + userId + '"的数据项？').then(function () {
        return deleteNjtUserRegister(userId)
      }).then(() => {
        this.getPage()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {
        this.$modal.msgError("删除失败")
      })
    },
    //编辑弹窗确定
    submitData() {
      updateNjtUserRegister(this.editObjects).then(response => {
        //刷新表格数据
        this.getPage()
        //弹窗提示
        this.$modal.msgSuccess(response.msg)
        //关闭弹窗
        this.dialogVisible = false
      })
    },
    //分页页码切换
    getPageByPageNum(num) {
      this.queryParams.pageNum = num;
      this.getPage();
    },
    // 分页查询
    getPage() {
      // 过滤空值参数，避免不必要的查询条件
      const params = {};
      Object.keys(this.queryParams).forEach(key => {
        if (this.queryParams[key] !== "" && this.queryParams[key] !== undefined) {
          params[key] = this.queryParams[key];
        }
      });

      listNjtUserRegister(params).then(response => {
        this.tableData = response.rows;
        this.total = response.total;
      }).catch(error => {
        this.$modal.msgError("数据加载失败");
        console.error("getPage error:", error);
      });
    },
    /** 切换搜索内容显示/隐藏方法 */
    toggleContentHandle() {
      this.toggleContent = !this.toggleContent
    },
    /** 打开编辑对话框方法 */
    openDialog(objData) {
      Object.assign(this.editObjects, objData)
      this.dialogVisible = true;
    },
    handleExport(){
      this.download('/nongjt/userRegister/export', {
        ...this.queryParams
      }, `会员注册信息_${new Date().getTime()}.xlsx`)
    },

    /**
     * 批量删除方法
     */
    handleBatchDelete() {
      // 获取选中的行数据
      const selection = this.$refs.table.selection;

      // 检查是否有选中项
      if (!selection || selection.length === 0) {
        this.$modal.msgWarning("请至少选择一条数据进行删除");
        return;
      }

      // 提取选中项的ID
      const userIds = selection.map(item => item.id);

      // 确认删除
      this.$modal.confirm(`是否确认删除这${userIds.length}条选中的数据？`).then(() => {
        // 创建删除Promise数组
        const deletePromises = userIds.map(id => deleteNjtUserRegister(id));
        // 并行执行所有删除操作
        return Promise.all(deletePromises);
      }).then(() => {
        // 删除成功后的处理
        this.getPage();
        this.$modal.msgSuccess("批量删除成功");
      }).catch(() => {
        // 删除失败后的处理
        this.$modal.msgError("批量删除失败");
      });
    },

    /**
     * 重置查询条件方法
     */
    resetQuery() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 5,
        companyName: "",
        mobilePhone: "",
        memberFlag: undefined,
        userStatus: undefined,
        completionTime: "",
        trialTime: "",
        purchaseTime: "",
        expirationDate: ""
      };
      this.getPage();
    }
  }
}
</script>
